import asyncio
from concurrent.futures import ThreadPoolExecutor

from controller import base_handler
from database import database_mgr
from database.database_mgr import get_database_conf

tpe: ThreadPoolExecutor = ThreadPoolExecutor(20)


class SelectHandler(base_handler.BaseHandler):
    def get(self):
        db_conf = get_database_conf()
        options = []

        label = "%s:%d/%s" % (db_conf.db_address, db_conf.db_port, db_conf.db_name)
        options.append({"value": "default", "label": label, "db_addr": db_conf.db_address, "db_port": db_conf.db_port,
                        "db_name": db_conf.db_name,
                        "db_type": db_conf.db_type})

        res = {"status": 0, "message": "ok", "data": {"value": "default", "options": options}}

        self.set_response(res, 200)


class DbListHandler(base_handler.BaseHandler):
    async def get(self):
        global tpe
        loop = asyncio.get_running_loop()
        res = await loop.run_in_executor(tpe, database_mgr.get_schema_list)

        self.set_response(res, 200)


class TableListHandler(base_handler.BaseHandler):

    async def get(self):
        global tpe
        db_name = self.get_query_argument("db_name", None)
        if db_name is None:
            res = {"status": 1, "message": "[db_name]参数缺失", "data": {}}
            self.set_response(res, 200)
            return
        loop = asyncio.get_running_loop()
        res = await loop.run_in_executor(tpe, database_mgr.get_table_list, db_name)

        self.set_response(res, 200)


class FieldListHandler(base_handler.BaseHandler):

    async def get(self):
        db_name = self.get_query_argument("db_name", None)
        if db_name is None:
            res = {"status": 1, "message": "[db_name]参数缺失", "data": {}}
            self.set_response(res, 200)
            return
        table_name = self.get_query_argument("table_name", None)
        if table_name is None:
            res = {"status": 1, "message": "[table_name]参数缺失", "data": {}}
            self.set_response(res, 200)
            return

        loop = asyncio.get_running_loop()
        res = await loop.run_in_executor(tpe, database_mgr.get_field_list, db_name, table_name)

        self.set_response(res, 200)
